package eu.webhib.webblog.gui.controller;

import eu.webhib.frmwrk.jsf.exception.ExceptionUtil;
import eu.webhib.frmwrk.jsf.utils.JsfUtil;
import java.util.Map;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;

@ManagedBean(name = "err")
@RequestScoped
public class Error {

   private static final Logger log = Logger.getLogger(Error.class);
   private Map<String, Object> reqMap;

   public Error() {
      log.info("Error");
      reqMap = FacesContext.getCurrentInstance().getExternalContext().getRequestMap();
      for (String key : reqMap.keySet()) {
         log.info(" " + key);
      }
   }

   public String getExceptionLog() {
      log.info("getExceptionLog");
      Throwable t = getException();
      if (t == null) {
         return getMessage();
      }
      String ret = t.toString();
      if (t.getCause() != null) {
         t = t.getCause();
      }
      ret += "\n" + ExceptionUtil.getStackTrace(t);
      return ret;
   }

   private Throwable getException() {
      log.info("getException");

      /** The exception information is either attached to the request
       * (if it was triggered by the error page in the web.xml) or stored in the session
       * (if it was a redirect triggered by the ApplExceptionHandler)
       */
      Throwable t = (Throwable) reqMap.get("javax.servlet.error.exception");
      if (t == null) {
         t = (Throwable) JsfUtil.getSessionAttr(JsfUtil.SESSION_EXCEPTION_ATTRIBUTE);
      }
      return t;
   }

   private String getMessage() {
      log.info("getMessage");
      return (String) reqMap.get("javax.servlet.error.message");
   }

   public boolean getIsTest() {
      return !JsfUtil.isProductionStage();
   }
}
